﻿/// <reference path="//Microsoft.WinJS.1.0/js/base.js" />
/// <reference path="//Microsoft.WinJS.1.0/js/ui.js" />
(function () {

    var citiesList = new WinJS.Binding.List([]);

    var loadCities = function () {
        var citiesDTOs = Data.getCities();

        var currentCount = citiesList.dataSource.list.length
        citiesList.dataSource.list.splice(0, currentCount);

        for (var i = 0; i < citiesDTOs.length; i++) {
            citiesList.push(citiesDTOs[i]);
        }
    };

    var employmentTypeList = new WinJS.Binding.List([]);

    var loadEmploymentTypes = function () {

        var currentCount = employmentTypeList.dataSource.list.length
        employmentTypeList.dataSource.list.splice(0, currentCount);

        var employmentTypeDTOs = Data.getEmploumentOptions();

        for (var i = 0; i < employmentTypeDTOs.length; i++) {
            employmentTypeList.push(employmentTypeDTOs[i]);
        }
    };

    var sectorsList = new WinJS.Binding.List([]);

    var loadSectors = function () {
        var sectorsDTOs = Data.getSectors();

        var currentCount = sectorsList.dataSource.list.length
        sectorsList.dataSource.list.splice(0, currentCount);

        for (var i = 0; i < sectorsDTOs.length; i++) {
            sectorsList.push(sectorsDTOs[i]);
        }
    };

    var jobOfferList = new WinJS.Binding.List([]);
    var hashedValues = [];

    var loadJobOffers = function (query) {

        if (hashedValues[query]) {
            jobOfferList = hashedValues[query];
        }
        else {

            var currentCount = jobOfferList.dataSource.list.length
            jobOfferList.dataSource.list.splice(0, currentCount);

            var feedburnerUrl = "http://www.jobtiger.bg/rss/jobs.php?ln=2" + query;
            var feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json&num=999&q=" + encodeURIComponent(feedburnerUrl);

            WinJS.xhr({
                type: "GET",
                url: feedUrl,
                headers: { "Content-type": "application/xml" },
            }).then(function complete(result) {

                var jsonData = JSON.parse(result.response);
                if (jsonData.responseData != null) {
                    for (var i = 0; i < jsonData.responseData.feed.entries.length; i++) {
                        jobOfferList.push(jsonData.responseData.feed.entries[i]);
                    }

                    hashedValues[query] = jobOfferList;
                }
            }, function (e) {
                message = new Windows.UI.Popups.MessageDialog("Възникна грешка при взимането на отдалечените данни. Моля проверете интернет връзката и опитайте отново!");
                if (e.message != undefined) {  // If the URL is really malformed or blank.
                    console.log(e.message);
                    message.showAsync();
                }
                else if (e.statusText != undefined) { // If an XmlHttpRequest is made.
                    console.log(e.message);
                    message.showAsync();
                }
                else {
                    message.content = "Възникна проблем при обработката на Вашата заявка. Моля опитайте отново! ";
                    message.showAsync();
                }
            });

            jobOfferList.notifyReload();
        }
    }

    var searchQuery = { queryText: "" };

    var filteredJobOffers = jobOfferList.createFiltered(function (item) {
        var queryIndex = JSON.stringify(item).indexOf(searchQuery.queryText);
        var isSelected = queryIndex > -1;
        return isSelected;
    });

    var changeSearchText = function (text) {
        searchQuery.queryText = text;
        jobOfferList.notifyReload();
    };

    var searchList = new WinJS.Binding.List([]);

    var createSearchList = function (collection) {

        var searchesDTOs = collection;

        var currentCount = searchList.dataSource.list.length
        searchList.dataSource.list.splice(0, currentCount);

        for (var i = 0; i < searchesDTOs.length; i++) {
            searchList.push(searchesDTOs[i]);
        }
    };

    WinJS.Namespace.define("ViewModels", {
        loadCities: loadCities,
        cities: citiesList,
        loadEmploymentTypes: loadEmploymentTypes,
        employmentTypes: employmentTypeList,
        loadSectors: loadSectors,
        sectors: sectorsList,
        loadJobOffers: loadJobOffers,
        jobOffers: jobOfferList,
        searchJobOffers: filteredJobOffers,
        submitSearchText: changeSearchText,
        searchQuery: searchQuery,
        createSearchList: createSearchList,
        searchList: searchList
    });
})();